package com.song.studylineserver.controller;

import com.song.studylineserver.domain.File;
import com.song.studylineserver.domain.R;
import com.song.studylineserver.exception.file.FileSizeLimitExceededException;
import com.song.studylineserver.service.FileService;
import com.song.studylineserver.util.FileUtils;
import com.song.studylineserver.util.Loggers;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Api(tags = "图片")
@RestController
@RequestMapping("/img")
public class FileController {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileService sysFileService;

    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    public R<File> upload(MultipartFile file)
    {
        try
        {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            File sysFile = new File();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }
}
